package com.tw.management.utlis;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import com.tw.management.entity.User;

/**
 * 密码加密类
 * 
 * @author Tangw
 * @version 1.0
 *
 */
public class PasswordAndSaltHelper {

	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator(); // 随机数

	private String algorithmName = "md5"; // 加密算法
	private static final  int ITERATIONS = 2; // 散列2次

	/**
	 * 加密密码
	 * 
	 * @param user
	 */
	public void encryptPassword(User user) {

		user.setSalt(randomNumberGenerator.nextBytes().toHex());

		String newPassword = new SimpleHash(algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), ITERATIONS).toHex();

		user.setPassword(newPassword);
	}

	/**
	 * 解密密码
	 * 
	 * @param user
	 */
	public String decryptPassword(User user) {

		return new SimpleHash(algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), ITERATIONS).toHex();

	}
}
